package cn.kgc.shiro.web.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/12/6
 * @description shiro集成web环境配置
 */
@Configuration
public class ShiroWebConfig {

    //  shiro  Filter
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //  声明shiro的过滤规则
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        // 放行登录请求   使用匿名过滤器  本质放行请求
        map.put("/user/login","anon");
        //  所有的请求都要经过    FormAuthenticationFilter   authc
        map.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // 没有认证的请求  跳转路径
        shiroFilterFactoryBean.setLoginUrl("/user/toLogin");

        return shiroFilterFactoryBean;
    }


    // 安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(CustomerRealm customerRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(customerRealm);
        return defaultWebSecurityManager;
    }


    // 自定义  Realm
    @Bean
    public CustomerRealm customerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(10);
        customerRealm.setCredentialsMatcher(md5);
        return customerRealm;
    }


}
